//
//  ZCHttpTool.m
//  kangbs
//
//  Created by 高睿婕 on 2018/8/12.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCHttpTool.h"
#import "ZCUserTokenModel.h"

#ifdef DEBUG
#define ZCHttpLog(s, ...)                                                         \
    NSLog(@"[%@：in line: %d]-->[message: %@]",                                   \
        [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, \
        [NSString stringWithFormat:(s), ##__VA_ARGS__])
#else
#define ZCHttpLog(s, ...)
#endif


//设置网络允许的超时时间
static NSTimeInterval requestTimeout = 60;

//基础URL
static NSString *zc_baseURL = hostUaaURL;

@implementation ZCHttpTool
+ (void)updateBaseURL:(NSString *)url {
    zc_baseURL = url;
}

+ (AFHTTPSessionManager *)managerInit {
    
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    //初始化baseURL
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:hostURL]];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = requestTimeout;
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[
                                                                              @"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/javascript",
                                                                              @"text/plain"
                                                                              ]];
    //请求头设置
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:loginToken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    
    return manager;
}

//获取可用token
+ (void)getRefreshTokenWithURL:(NSString *)url params:(NSDictionary *)params success:(httpSuccessBlock)success failure:(httpFailureBlock)failure {
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    //初始化baseURL
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:hostUaaURL]];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = requestTimeout;
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[
                                                                              @"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/javascript",
                                                                              @"text/plain"
                                                                              ]];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task,error);
        }
    }];
}


+ (void)getEffectiveTokenStyleForGetWithURL:(NSString *)url params:(NSDictionary *)params success:(httpSuccessBlock)success failure:(httpFailureBlock)failure {
    NSString *refresh_Token = [[NSUserDefaults standardUserDefaults] objectForKey:refreshToken];
    NSString *expires = [[NSUserDefaults standardUserDefaults] objectForKey:effectiveTime];
    NSString *createTime = [[NSUserDefaults standardUserDefaults] objectForKey:tokenCreateTime];
    NSTimeInterval tokenTime = [createTime doubleValue] / 1000;
    //时区
    NSDate *currentData = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:currentData];
    NSDate *tokenDate = [[NSDate dateWithTimeIntervalSince1970:tokenTime] dateByAddingTimeInterval:interval];
    
    NSDate *nowDate = [[NSDate date] dateByAddingTimeInterval:interval];
    double cha = [nowDate timeIntervalSinceDate:tokenDate];
    if (cha > [expires doubleValue]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:loginToken];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:@"devops" forKey:@"client_id"];
        [param setObject:@"devops" forKey:@"client_secret"];
        [param setObject:@"refresh_token" forKey:@"grant_type"];
        [param setObject:refresh_Token forKey:@"refresh_token"];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showWithStatus:@"正在重新登录"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self getRefreshTokenWithURL:UserToken params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                ZCUserTokenModel *userTokenModel = [ZCUserTokenModel yy_modelWithDictionary:responseObject];
                if (userTokenModel.access_token.length > 0) {
                    [SVProgressHUD showSuccessWithStatus:@"重新登录成功"];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.access_token forKey:loginToken];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.refresh_token forKey:refreshToken];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.expires_in forKey:effectiveTime];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.gmt_create forKey:tokenCreateTime];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.accountId forKey:AccountId];
                    [[NSUserDefaults standardUserDefaults] synchronize];
//                    NSLog(@"222===%@",userTokenModel.access_token);
                    AFHTTPSessionManager *manager = [self managerInit];
//                    NSLog(@"111---%@",manager.requestSerializer.HTTPRequestHeaders[@"Authorization"]);
                    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        if (success) {
                            success(task,responseObject);
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        if (failure) {
                            failure(task,error);
                        }
                        
                    }];
                }else {
                    [SVProgressHUD showErrorWithStatus:responseObject[@"message"]];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }];
        });
    }else {
        AFHTTPSessionManager *manager = [self managerInit];
        [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(task,error);
            }
            
        }];
    }
}


+ (void)getEffectiveTokenStyleForPostWithURL:(NSString *)url params:(NSDictionary *)params success:(httpSuccessBlock)success failure:(httpFailureBlock)failure {
    NSString *refresh_Token = [[NSUserDefaults standardUserDefaults] objectForKey:refreshToken];
    NSString *expires = [[NSUserDefaults standardUserDefaults] objectForKey:effectiveTime];
    NSString *createTime = [[NSUserDefaults standardUserDefaults] objectForKey:tokenCreateTime];
    NSTimeInterval tokenTime = [createTime doubleValue] / 1000;
    //时区
    NSDate *currentData = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:currentData];
    NSDate *tokenDate = [[NSDate dateWithTimeIntervalSince1970:tokenTime] dateByAddingTimeInterval:interval];
    
    NSDate *nowDate = [[NSDate date] dateByAddingTimeInterval:interval];
    double cha = [nowDate timeIntervalSinceDate:tokenDate];
    if (cha > [expires doubleValue]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:loginToken];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:@"devops" forKey:@"client_id"];
        [param setObject:@"devops" forKey:@"client_secret"];
        [param setObject:@"refresh_token" forKey:@"grant_type"];
        [param setObject:refresh_Token forKey:@"refresh_token"];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showWithStatus:@"正在重新登录"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self getRefreshTokenWithURL:UserToken params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                ZCUserTokenModel *userTokenModel = [ZCUserTokenModel yy_modelWithDictionary:responseObject];
                if (userTokenModel.access_token.length > 0) {
                    [SVProgressHUD showSuccessWithStatus:@"重新登录成功"];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.access_token forKey:loginToken];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.refresh_token forKey:refreshToken];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.expires_in forKey:effectiveTime];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.gmt_create forKey:tokenCreateTime];
                    [[NSUserDefaults standardUserDefaults] setObject:userTokenModel.accountId forKey:AccountId];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    AFHTTPSessionManager *manager = [self managerInit];
                    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        if (success) {
                            success(task,responseObject);
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        if (failure) {
                            failure(task,error);
                        }
                    }];
                }else {
                    [SVProgressHUD showErrorWithStatus:responseObject[@"message"]];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }];
        });
    }else {
        AFHTTPSessionManager *manager = [self managerInit];
        [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(task,error);
            }
        }];
    }
}

+ (void)getWithURL:(NSString *)url params:(NSDictionary *)params success:(httpSuccessBlock)success failure:(httpFailureBlock)failure {
    
    [self getEffectiveTokenStyleForGetWithURL:url params:params success:success failure:failure];
   
}

+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params success:(httpSuccessBlock)success failure:(httpFailureBlock)failure {
    
    [self getEffectiveTokenStyleForPostWithURL:url params:params success:success failure:failure];
    
}


@end
